package com.taotao.cart.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.taotao.cart.pojo.Cart;
import com.taotao.cart.pojo.ItemVO;
import com.taotao.common.service.HttpClientService;
import com.taotao.common.utils.CookieUtils;

/**
 * 未登陆状态下的购物操作（Cookie的实现）
 * 
 * @author joedy
 *
 */
@Service
public class CookieCartService {

	@Autowired
	private HttpClientService httpClientService;

	private static final String CART_COOKIE_NAME = "TT_CART";

	private static final ObjectMapper MAPPER = new ObjectMapper();

	/**
	 * 添加购物车
	 * 
	 * @param itemId
	 * @param id
	 */
	public void saveCart(Long itemId, HttpServletRequest request, HttpServletResponse response) {
		Map<Long, Cart> carts = queryCookieCarts(request);
		// 根据商品id获取购物车集合中的购物记录
		Cart cart = carts.get(itemId);

		// 没有该记录,新增购物车记录
		if (cart == null) {
			cart = new Cart();
			cart.setItemId(itemId);
			cart.setNum(1);
			// 查询商品信息
			ItemVO itemVO = this.httpClientService.doGet("http://manage.taotao.com/rest/api/item/" + itemId,
					new TypeReference<ItemVO>() {
					});
			cart.setItemImage(itemVO.getImages()[0]);
			cart.setItemPrice(itemVO.getPrice());
			cart.setItemTitle(itemVO.getTitle());
			cart.setCreated(new Date());
			cart.setUpdated(cart.getCreated());
			// 执行新增操作
			carts.put(itemId, cart);
		} else {
			// 有该记录更新数量
			cart.setNum(cart.getNum() + 1);
			cart.setUpdated(new Date());
		}
		saveCookieCarts(request, response, carts);
	}

	/**
	 * 查询购物信息
	 * 
	 * @param id
	 * @return
	 */
	public List<Cart> queryCarts(HttpServletRequest request) {
		// 查询购物车中所有记录
		Map<Long, Cart> carts = this.queryCookieCarts(request);
		// 处理结果集
		Collection<Cart> values = carts.values();
		// 包装成List<Cart>
		return new ArrayList<>(values);
	}

	/**
	 * 根据用户id和商品id更新数量
	 * 
	 * @param itemId
	 * @param userId
	 * @param num
	 */
	public void updateNum(Long itemId, Integer num, HttpServletRequest request, HttpServletResponse response) {
		// 查询购物车记录
		Map<Long, Cart> carts = this.queryCookieCarts(request);
		// 根据商品id获取购物记录
		Cart cart = carts.get(itemId);
		// 设置更新的参数
		cart.setNum(num);
		cart.setUpdated(new Date());
		// 执行更新
		this.saveCookieCarts(request, response, carts);
	}

	/**
	 * 删除购物车
	 * 
	 * @param itemId
	 * @param userId
	 */
	public void deleteCart(Long itemId, HttpServletRequest request, HttpServletResponse response) {

		Map<Long, Cart> carts = this.queryCookieCarts(request);
		// 根据商品id删除对应的购物车记录
		carts.remove(itemId);
		// 执行删除
		this.saveCookieCarts(request, response, carts);
	}

	private Map<Long, Cart> queryCookieCarts(HttpServletRequest request) {
		// 查询cookie中的购物车
		String jsonData = CookieUtils.getCookieValue(request, CART_COOKIE_NAME);
		// 如果cookie中的购物车记录为空的话，创建新的购物车集合
		if (StringUtils.isEmpty(jsonData)) {
			return new HashMap<>();
		}
		try {
			// 如果有反序列化
			return MAPPER.readValue(jsonData, new TypeReference<Map<Long, Cart>>() {
			});
		} catch (IOException e) {
			// 如果有异常，创建新的购物车集合
			return new HashMap<>();
		}
	}

	private void saveCookieCarts(HttpServletRequest request, HttpServletResponse response, Map<Long, Cart> carts) {
		try {
			CookieUtils.setCookie(request, response, CART_COOKIE_NAME, MAPPER.writeValueAsString(carts));
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
	}

}
